const Answer = require('../model/answer')


class AnswerCtl {
  //检查答案是否存在
  async checkAnswerExist(ctx, next) {
    const answer = await Answer.findById(ctx.params.id)
    if(!answer) {
      ctx.throw(404, "答案不存在")
    }
    if( ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
      ctx.throw(404, "该问题下此答案不存在")
    }
    ctx.state.answer = answer
    await next()
  }
  //检查问题拥有着

  async checkAnswerer (ctx, next) {
    const { answer } = ctx.state
    if(answer.answerer.toString() !== ctx.state.user._id) {
      ctx.throw(403,'没有权限')
    }
    await next()
  }




  async find(ctx) {
    const { per_page = 3, page = 1 } = ctx.query
    const perpage = Math.max(per_page * 1, 1)
    const pages = Math.max(page * 1, 1) - 1
    const q = new RegExp(ctx.query.q)
    // $or: [{ content: q }, { description: q }]
    ctx.body = await Answer.find({ content: q, questionId: ctx.params.questionId }).limit(perpage).skip(pages * perpage)
  }
  async findById(ctx) {
    const { fields = '' } = ctx.query
    const selectField = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const answer = await Answer.findById(ctx.params.id).select(selectField).populate('answerer')
    ctx.body = answer
  }
  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true },
    })
    const answer = await new Answer({...ctx.request.body, answerer: ctx.state.user._id, questionId: ctx.params.questionId}).save()
    ctx.body = answer
  }

  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false },
    })
      await ctx.state.answer.update(ctx.request.body)
     ctx.body = ctx.state.answer
       
     
  }
  async del(ctx) {
    await answer.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }

  async listanswerFollower(ctx) {
    const user = await User.find({followingTopic: ctx.params.id})
    ctx.body = user
  }
}
module.exports = new AnswerCtl()